package com.vchangyi.springboot.common.interceptor;

import com.vchangyi.springboot.common.utils.AesUtil;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Pattern;

@Intercepts({
        @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})
})
@Component
public class EncryptionInterceptor implements Interceptor {

    private static final Pattern EMAIL_OR_MOBILE_PATTERN = Pattern.compile(".*?(email|mobile).*?", Pattern.CASE_INSENSITIVE);
    private static final Map<Object, Map<String, Object>> BACKUP_MAP = new HashMap<>();

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        MappedStatement ms = (MappedStatement) invocation.getArgs()[0];
        Object parameter = invocation.getArgs()[1];
        SqlCommandType commandType = ms.getSqlCommandType();

        if (commandType == SqlCommandType.INSERT || commandType == SqlCommandType.UPDATE) {
            if (parameter != null) {
                backupOriginalFields(parameter);
                encryptFields(parameter);
            }
        }

        try {
            return invocation.proceed();
        } finally {
            if (commandType == SqlCommandType.INSERT || commandType == SqlCommandType.UPDATE) {
                restoreOriginalFields(parameter);
            }
        }
    }

    private void backupOriginalFields(Object obj) throws IllegalAccessException {
        Class<?> clazz = obj.getClass();
        Field[] fields = clazz.getDeclaredFields();
        Map<String, Object> backup = new HashMap<>();

        for (Field field : fields) {
            field.setAccessible(true);
            String fieldName = field.getName();
            if (field.get(obj) instanceof String) {
                backup.put(fieldName, field.get(obj));
            }
        }

        BACKUP_MAP.put(obj, backup);
    }

    private void encryptFields(Object obj) throws Exception {
        Class<?> clazz = obj.getClass();
        Field[] fields = clazz.getDeclaredFields();

        for (Field field : fields) {
            field.setAccessible(true);
            String fieldName = field.getName();
            if (EMAIL_OR_MOBILE_PATTERN.matcher(fieldName).matches() && field.get(obj) instanceof String) {
                String value = (String) field.get(obj);
                field.set(obj, AesUtil.encrypt(value));
            }
        }
    }

    private void restoreOriginalFields(Object obj) throws IllegalAccessException {
        Map<String, Object> backup = BACKUP_MAP.get(obj);
        if (backup != null) {
            Class<?> clazz = obj.getClass();
            Field[] fields = clazz.getDeclaredFields();

            for (Field field : fields) {
                field.setAccessible(true);
                String fieldName = field.getName();
                if (backup.containsKey(fieldName)) {
                    field.set(obj, backup.get(fieldName));
                }
            }
        }
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
        // 可以在这里设置一些属性
    }
}